package com.api.gbhg.zengping.web;

import com.alibaba.fastjson.JSON;
import com.api.gbhg.liuwenbo.utils.AlgorithmUtil;
import com.api.gbhg.zengping.dao.LeadingPortalsDao;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import com.api.gbhg.zengping.page.PageInfo;
import com.api.gbhg.zengping.utils.RecursionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

/**
 * @program: gbhg-oa
 * @author: Mr.zeng
 * @create: 2021-01-18 14:01
 *
 * 领导门户接口
 **/
public class LeadingPortalsAction {
    public static final Logger LOGGER = LoggerFactory.getLogger("gbhg");
    private final LeadingPortalsDao leadingPortalsDao=new LeadingPortalsDao();
    private PropertyManagementCostDao rmcd=new PropertyManagementCostDao();


    /**
     * 领导门户重点项目  项目名称：xmmc  所属单位名称：ssdw 预算金额/万：ysje 执行百分率：zxl
     * @param map   pageNum,pageSize,ysnd,sbdw
     * @return
     */
    @POST
    @Path("/getKeyProject")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getKeyProject(Map<String,Object> map){
        RecordSet rsKeyProject = leadingPortalsDao.selectKeyProjectList(map);
        Map<String,Object>[] list=new HashMap[rsKeyProject.getArray().size()];
        int i=0;
        while (rsKeyProject.next()){
            list[i]=new HashMap<>();
            list[i].put("lcjlsqjlid",rsKeyProject.getString("requestId"));
            list[i].put("xmmc",rsKeyProject.getString("xmmin"));
            //申报单位
            RecordSet sbdw = rmcd.getSBDWById(rsKeyProject.getInt("sbdw"));
            sbdw.next();
            list[i].put("ssdw",sbdw.getString("SUBCOMPANYNAME"));
            list[i].put("ysje",rsKeyProject.getDouble("yszje"));
            String requestId = rsKeyProject.getString("requestId");
            RecordSet rsSyed = leadingPortalsDao.queryExecuteRate(requestId);
            double syed=0.0;
            while (rsSyed.next()){
                syed=rsSyed.getDouble("syed");
            }
            double yszje= (double) list[i].get("ysje");
            //执行百分率
            list[i].put("zxl",getPercent2(yszje-syed,yszje));
            i++;
        }
        PageInfo<String> pageInfo=new PageInfo();
        RecordSet recordSet = leadingPortalsDao.selectKeyProjectCount(map);
        recordSet.next();
        pageInfo.setTotal(recordSet.getInt("num"));
        pageInfo.setPageNum((Integer) map.get("pageNum"));
        pageInfo.setPageSize((Integer) map.get("pageSize"));
        pageInfo.setList(list);
        return JSON.toJSONString(pageInfo);
    }

    /**
     * 预算执行率
     * @param map
     * @return
     */
    @POST
    @Path("/getImplementationRate")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getImplementationRate(Map<String,Object> map){
        Map<String,Object> list=new HashMap<>();
       // 查询选中单位下所有申报单位
        List dw=new ArrayList();
        dw.add(map.get("sbdw"));
        List<Integer> subList = new RecursionUtil().getSubList(dw);
        map.put("sbdw",RecursionUtil.listToString1(subList,','));
        //预算来源
       final int ysly=1;
        RecordSet rs = leadingPortalsDao.queryCentralFinanceAppropriation(ysly,map);
        //收益
        String percentZy=null;
        //年平均用值
        String yearAvg=null;
        while (rs.next()){
            double je = rs.getDouble("je");
            double syed = rs.getDouble("syed");
             percentZy = LeadingPortalsAction.getPercent2(je-syed, syed);

            yearAvg = AlgorithmUtil.getYearAvgImplRate((Integer) map.get("nd"),je);
        }
        //中央财政拨款预算执行率
        //当年执行率
        list.put("zycz_dnzxl",percentZy);
        list.put("zycz_dnzxlRait",yearAvg);
        //上年结转执行率
        list.put("zycz_snjzzxl",percentZy);
        list.put("zycz_snjzzxlRait",yearAvg);

       final int dfzcbk=3;
        RecordSet rs1 = leadingPortalsDao.queryCentralFinanceAppropriation(dfzcbk,map);
        String percentDf=null;
        String yearAvgdf=null;
        while (rs1.next()){
            double je = rs1.getDouble("je");
            double syed = rs1.getDouble("syed");
            percentDf = LeadingPortalsAction.getPercent2(je-syed, syed);
            yearAvgdf = AlgorithmUtil.getYearAvgImplRate((Integer) map.get("nd"),rs1.getDouble("je"));
        }
        list.put("dfcz_dnzxl",percentDf);//当年执行率
        list.put("dfcz_dnzxlRait",yearAvgdf);
        list.put("dfcz_snjzzxl",yearAvgdf);//上年结转执行率
        list.put("dfcz_snjzzxlRait","0");
        return JSON.toJSONString(list);
    }

    /**
     * 返回当前用户权限所查看的单位
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/getCurrentUserDepartment")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getCurrentUserDepartment(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        //得到当前用户
        User user = HrmUserVarify.getUser(request, response);
        int userId = user.getUID(); //得到当前用户id
        // 返回当前用户所在分部的上层分部id
        RecordSet rs = leadingPortalsDao.selectCurrentUserReturnSubcompany(userId);
        Map map=new HashMap();
        while (rs.next()){
            // 得到当前单位
            List dw = new ArrayList();
            dw.add(rs.getInt("subcompanyid1"));
            Map[] subMap = new RecursionUtil().getCurrentDept(dw);
            return JSON.toJSONString(subMap);
        }
        if(userId==1){
            //系统管理员,直接返回拱北海关
            List dw = new ArrayList();
            dw.add(0);
            Map[] subMap = new RecursionUtil().getCurrentDept(dw);
            return JSON.toJSONString(subMap);
        }
        return JSON.toJSONString(map);
    }


    /**
     * 返回当前用户权限所查看的单位（判断是否独立核算单位）
     * @param request
     * @param response
     * @param param  0 独立核算单位  1 非独立核算
     * @return
     */
    @POST
    @Path("/getCurrentUserDepartmentIsIndependent")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getCurrentUserDepartmentIsIndependent(@Context HttpServletRequest request, @Context HttpServletResponse response,Map<String,Integer> param) {
        User user = HrmUserVarify.getUser(request, response);  //得到当前用户
        int userId = user.getUID(); //得到当前用户id
        // 返回当前用户所在分部的上层分部id
        RecordSet rs = leadingPortalsDao.selectCurrentUserReturnSubcompany(userId);
        Map map=new HashMap();
        while (rs.next()){
            // 得到当前单位
            List dw = new ArrayList();
            dw.add(rs.getInt("subcompanyid1"));
            //判断是否是独立核算单位
            RecordSet rsIndependent=new RecordSet();
            String sqlIndependent="select * from  uf_dwsxpz where xzxtdw="+dw.get(0)+" and sfwdlhsdw=1";
            rsIndependent.executeQuery(sqlIndependent);
            rsIndependent.next();
            // 0独立核算&&size大于0
            if(rsIndependent.getArray().size()>0&&param.get("status")==0){
                Map[] subMap = new RecursionUtil().getCurrentDept(dw);
                return JSON.toJSONString(subMap);
            }
            // 1非独立核算&&size==0
            if(rsIndependent.getArray().size()==0&&param.get("status")==1){
                Map[] subMap = new RecursionUtil().getCurrentDept(dw);
                return JSON.toJSONString(subMap);
            }
            //非独立核算单位
            Map res=new HashMap();
            res.put("isIndependent",false);
            return JSON.toJSONString(res);
        }
        if(userId==1){
            //系统管理员,直接返回拱北海关
            List dw = new ArrayList();
            dw.add(0);
            Map[] subMap = new RecursionUtil().getCurrentDept(dw);
            return JSON.toJSONString(subMap);
        }
        return JSON.toJSONString(map);
    }

    public static void main(String[] args) {
        //
        System.out.println(Math.abs(100-177.28));
        String percent2 = getPercent2(1, 177.28);
        System.out.println(percent2);
    }

    public static int getYearOnDay(){
        Date date=new Date();
        Calendar ca=Calendar.getInstance();
        ca.setTime(date);
        return ca.get(Calendar.DAY_OF_YEAR);
    }
    /**
     * 方式二：使用java.text.DecimalFormat实现
     * @param x 除
     * @param y 被除
     * x/y 计算百分率 (执行率)
     * @return
     */
    public static String getPercent2(double x, double y) {
        if(y==0){
            return "0%";
        }
        BigDecimal b1=new BigDecimal(x);
        BigDecimal b2=new BigDecimal(y);
        BigDecimal divide = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(2);
        return percent.format(divide.doubleValue());
    }
}
